#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    ui->lineEdit->setPlaceholderText("请输入新增的列名称");
    //创建3行3列
    ui->tableWidget->insertRow(0);
    ui->tableWidget->insertRow(1);
    ui->tableWidget->insertRow(2);

    ui->tableWidget->insertColumn(0);
    ui->tableWidget->insertColumn(1);
    ui->tableWidget->insertColumn(2);

    //设置每一列的名称
    ui->tableWidget->setHorizontalHeaderItem(0, new QTableWidgetItem("学号"));
    ui->tableWidget->setHorizontalHeaderItem(1, new QTableWidgetItem("姓名"));
    ui->tableWidget->setHorizontalHeaderItem(2, new QTableWidgetItem("电话号"));

    //添加初始数据
    ui->tableWidget->setItem(0, 0, new QTableWidgetItem("2000"));
    ui->tableWidget->setItem(0, 1, new QTableWidgetItem("zhangsan"));
    ui->tableWidget->setItem(0, 2, new QTableWidgetItem("000-0000-0000"));

    ui->tableWidget->setItem(1, 0, new QTableWidgetItem("2001"));
    ui->tableWidget->setItem(1, 1, new QTableWidgetItem("lisi"));
    ui->tableWidget->setItem(1, 2, new QTableWidgetItem("123-4567-8901"));

    ui->tableWidget->setItem(2, 0, new QTableWidgetItem("2002"));
    ui->tableWidget->setItem(2, 1, new QTableWidgetItem("wangwu"));
    ui->tableWidget->setItem(2, 2, new QTableWidgetItem("342-4483-1992"));
}

Widget::~Widget()
{
    delete ui;
}

//增加一行
void Widget::on_pushButton_add_row_clicked()
{
    //获取行数
    int row_count = ui->tableWidget->rowCount();
    //增加一行
    ui->tableWidget->insertRow(row_count);
}

//增加一列
void Widget::on_pushButton_column_add_clicked()
{
    //获取列数
    int column_count = ui->tableWidget->columnCount();
    //获取新增列的表头
    const QString str = ui->lineEdit->text();
    //如果为空的话，就不添加了
    if(str.isEmpty())
        return;
    //增加一列
    ui->tableWidget->insertColumn(column_count);
    //设置表头
    ui->tableWidget->setHorizontalHeaderItem(column_count, new QTableWidgetItem(str));
}

//删除选中行
void Widget::on_pushButton_row_del_clicked()
{
    //获取当前选中的行
    int row = ui->tableWidget->currentRow();
    //删除
    ui->tableWidget->removeRow(row);
}

//删除选中列
void Widget::on_pushButton_column_del_clicked()
{
    //获取当前选中的列
    int column = ui->tableWidget->currentColumn();
    //删除
    ui->tableWidget->removeColumn(column);
}
